import { Request, Response } from 'express';
import { prisma } from '@/config/database';
import { logger } from '@/utils/logger';
import ApiError from '@/utils/ApiError';
import catchAsync from '@/utils/catchAsync';

export class MessageController {
  // 获取聊天消息
  getMessages = catchAsync(async (req: Request, res: Response) => {
    const userId = (req as any).user?.id;
    const { page = 1, limit = 50 } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    // 获取另一个用户ID
    const otherUser = await prisma.user.findFirst({
      where: { id: { not: userId } },
      select: { id: true }
    });

    if (!otherUser) {
      throw new ApiError(404, '聊天对象不存在');
    }

    const messages = await prisma.message.findMany({
      where: {
        OR: [
          { senderId: userId, receiverId: otherUser.id },
          { senderId: otherUser.id, receiverId: userId }
        ]
      },
      include: {
        sender: {
          select: {
            id: true,
            username: true,
            nickname: true,
            avatar: true
          }
        },
        receiver: {
          select: {
            id: true,
            username: true,
            nickname: true,
            avatar: true
          }
        }
      },
      orderBy: { createdAt: 'desc' },
      skip,
      take: Number(limit)
    });

    res.json({
      success: true,
      data: messages.reverse() // 反转以获得正确的时间顺序
    });
  });

  // 发送消息
  sendMessage = catchAsync(async (req: Request, res: Response) => {
    const userId = (req as any).user?.id;
    const { content, type = 'text' } = req.body;

    if (!content || content.trim() === '') {
      throw new ApiError(400, '消息内容不能为空');
    }

    // 获取另一个用户ID
    const otherUser = await prisma.user.findFirst({
      where: { id: { not: userId } },
      select: { id: true }
    });

    if (!otherUser) {
      throw new ApiError(404, '聊天对象不存在');
    }

    const message = await prisma.message.create({
      data: {
        content: content.trim(),
        type,
        senderId: userId,
        receiverId: otherUser.id
      },
      include: {
        sender: {
          select: {
            id: true,
            username: true,
            nickname: true,
            avatar: true
          }
        },
        receiver: {
          select: {
            id: true,
            username: true,
            nickname: true,
            avatar: true
          }
        }
      }
    });

    logger.info(`消息发送成功`, { messageId: message.id, senderId: userId });

    res.status(201).json({
      success: true,
      data: message,
      message: '消息发送成功'
    });
  });

  // 标记消息为已读
  markAsRead = catchAsync(async (req: Request, res: Response) => {
    const userId = (req as any).user?.id;
    const { messageId } = req.params;

    const message = await prisma.message.findUnique({
      where: { id: messageId }
    });

    if (!message) {
      throw new ApiError(404, '消息不存在');
    }

    if (message.receiverId !== userId) {
      throw new ApiError(403, '只能标记接收到的消息为已读');
    }

    await prisma.message.update({
      where: { id: messageId },
      data: {
        isRead: true,
        readAt: new Date()
      }
    });

    res.json({
      success: true,
      message: '消息已标记为已读'
    });
  });

  // 标记所有消息为已读
  markAllAsRead = catchAsync(async (req: Request, res: Response) => {
    const userId = (req as any).user?.id;

    await prisma.message.updateMany({
      where: {
        receiverId: userId,
        isRead: false
      },
      data: {
        isRead: true,
        readAt: new Date()
      }
    });

    res.json({
      success: true,
      message: '所有消息已标记为已读'
    });
  });

  // 获取未读消息数量
  getUnreadCount = catchAsync(async (req: Request, res: Response) => {
    const userId = (req as any).user?.id;

    const count = await prisma.message.count({
      where: {
        receiverId: userId,
        isRead: false
      }
    });

    res.json({
      success: true,
      data: { count }
    });
  });
}

export const messageController = new MessageController();